package top.aicats.pattern.delegate.springmvc;

import top.aicats.pattern.delegate.springmvc.controller.MemberController;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class DispatcherServlet extends HttpServlet {
    private List<MyHandler> handlerList =new ArrayList<MyHandler>();

    public void init() {
        Class<?> memberClass = MemberController.class;
        try {
            handlerList.add(new MyHandler()
                    .setController(memberClass.newInstance())
                    .setMethod(memberClass.getMethod("getMemberById", new Class[]{Integer.class}))
                    .setUrl("/web/getMemberById.json"));
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    protected void service(HttpServletRequest req, HttpServletResponse response) {
        try {
            doDispatch(req, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void doDispatch(HttpServletRequest request, HttpServletResponse response) throws InvocationTargetException, IllegalAccessException {
        String uri =request.getRequestURI();
        MyHandler handler =null;
        for (MyHandler h: handlerList) {
            if (uri.equals(h.getUrl())) {
                handler = h;
                break;
            }
        }

        Object object = null;
        try {
            object = handler.getMethod().invoke(handler.getController(), request.getParameter("id"));
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    class MyHandler {
        private Object controller;
        private Method method;
        private String url;

        public Object getController() {
            return controller;
        }

        public MyHandler setController(Object controller) {
            this.controller = controller;
            return this;
        }

        public Method getMethod() {
            return method;
        }

        public MyHandler setMethod(Method method) {
            this.method = method;
            return this;
        }

        public String getUrl() {
            return url;
        }

        public MyHandler setUrl(String url) {
            this.url = url;
            return this;
        }




    }
}
